package br.usp.ime.mac.mico.dao;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;

import br.usp.ime.mac.mico.factories.JPADAOFactory;
import br.usp.ime.mac.mico.models.Sample;

// Metodos do banco de dados podem ser refatorados para JPADAO!
public class JPASampleDAO implements SampleDAO {

	private EntityManager manager;
	private EntityTransaction transaction; 

	public JPASampleDAO() {
		manager = this.openPersistence();
	}

	public EntityManager openPersistence() {
		if (manager == null || !manager.isOpen())
			manager = JPADAOFactory.getInstance().getFactory().createEntityManager();
		return (manager);
	}

	public void closePersistence() {
		manager.close();
	}

	public void atualizar(Sample sample) {
		transaction = manager.getTransaction();
		transaction.begin();
		manager.merge(sample);
		transaction.commit();
	}

	public Sample buscaPorId(long id) {
		return (manager.find(Sample.class, id));
	}

	public long salvar(Sample sample) {
		transaction = manager.getTransaction();
		transaction.begin();
		manager.persist(sample);
		transaction.commit();
		return(sample.getSampleId());
	}

}
